package myJs.user.soft.preDeal

import myJs.Implicits._
import myJs.Utils._
import myJs.myPkg.LayerOptions
import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.myPkg.jquery._
import myJs.tool.Pojo.PreDealSoft
import myJs.tool.Tool
import myJs.tool.Tool._
import myJs.user.soft.VideoCp
import myJs.user.soft.fileSelect.FileModal
import org.scalajs.dom._
import org.scalajs.dom.ext.Ajax
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import scalatags.Text.all._
import shared.Pojo._
import upickle.default._

import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("PreDeal")
object PreDeal {
  val formId = "form"
  val kind = PreDealSoft.nameStr
  val fileModalId = "fileModal"
  val tableId = "table"
  val timeFieldNames = List[String]()

  @JSExport("init")
  def init = {
    FileModal.init
    registerEvent
    bootStrapValidator
    $("#form").bv.revalidateField("missionName")
    refreshCalculateConfig
    VideoCp.Props(soft=PreDealSoft).render.renderIntoDOM(document.querySelector("#root"))
  }

  def getTrueFileName(fileName: String) = {
    val url = g.jsRoutes.controllers.MissionController.getTrueFileName().url.toString
    Ajax.get(url = s"${url.noCache}&fileName=${fileName}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDS
      rs("fileName")
    }
  }

  def refreshCalculateConfig = {
    val missionId = getMissionId
    if (missionId.nonBlank) {
      val url = g.jsRoutes.controllers.MissionController.getConfigData().url.toString
      Ajax.get(url = s"${url.noCache}&missionId=${missionId}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
        val rs = xhr.responseText.toJDJAn
        val data =  read[SharedPreDealData](JSON.stringify(rs))
        getTrueFileName(data.file).map { newFile =>
          val newData = data.copy(file = newFile)
          val newRs = JSON.parse(write(newData)).toJDJAn
          Tool.fillByNames(newRs.toMyJDS)
          Tool.fillByNameAndTriggers(newRs.toJDJAn)
          $(".myFile").foreach { y =>
            val name = $(y).nameAttr
            $("#form").bv.revalidateField(name)
          }
        }


      }
    }
  }

  def getMissionId = {
    g.missionId.toString
  }

  def registerEvent = {
    $(document.body).on("click", ".myFileSelectButton", "", (y: Element) => {
      val folder = $(y).dataFolder
      val fileName = $(y).dataFileName
      Tool.fileSelect(folder, fileName)
    })
    $(document.body).on("click", ".myFileSelect", "", (y: Element) => {
      val name = $(y).dataInputName
      val metDataFileName = Tool.getInputByName("file").myVal
      val lis = $(y).dataValue.split(";")
      $(".myFileSelect").removeClass("myCurrent")
      $(y).addClass("myCurrent")
      FileModal.fileSelectShow(lis)
    })
  }

  @JSExport("replaceMethodChange")
  def replaceMethodChange(y: Element) = {
    val myValue = $(y).find(">option:selected").`val`().toString
    replaceMethodChangeByValue(myValue)
  }

  def replaceMethodChangeByValue(myValue: String) = {
    myValue match {
      case "knn" =>
        $("#knn").show()
        $("#min").hide()
      case x if List("min", "rowMin").contains(x) =>
        $("#knn").hide()
        $("#min").show()
      case _ =>
        $("#knn").hide()
        $("#min").hide()
    }
  }

  @JSExport("fileSelect")
  def fileSelect(fileName: String) = {
    $(s"${formId}").findInputByName("file").`val`(fileName)
    $("#form").bv.revalidateField("file")
    $(s"#${fileModalId}").modal("hide")
  }

  @JSExport("myRun")
  def myRun = {
    val bv = $("#form").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val element = div(id := "content",
        span(id := "info", messages("running"),
          span(id := "progress", "。。。")), " ",
        img(src := "/assets/images/running2.gif", cls := "runningImage", width := 30, height := 20)
      ).render
      val layerOptions = LayerOptions.title(zhInfo).closeBtn(0).skin("layui-layer-molv").btn(js.Array())
      val index = layer.alert(element, layerOptions)
      val url = g.jsRoutes.controllers.SoftController.analysis().url.toString
      val formData = $(s"#form").serialize()
      Ajax.post(url = s"${url}", data = s"${formData}&kind=${PreDealSoft.nameStr}", headers = Map("Content-Type" -> "application/x-www-form-urlencoded")).map { xhr =>
        val rs = xhr.responseText.toJDJAn
        layer.close(index)
        val valid = rs("valid").toB
        if (valid) {
          window.location.href = g.jsRoutes.controllers.MissionController.missionManageBefore().url.toString
        } else {
          g.swal("Error", rs.myGet("message"), "error")
        }
      }
    }
  }

  def getId = {
    g.id.toString
  }

  def bootStrapValidator = {
    val url = g.jsRoutes.controllers.MissionController.missionNameCheck().url.toString
    val maxNumber = Double.MaxValue
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "missionName" -> {
          val info = messages("taskName")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${messages("exist")}",
                "url" -> url,
                "type" -> "POST",
                "delay" -> 1000,
                "data" -> js.Dictionary(
                  "kind" -> kind
                )
              ),
            )
          )
        },
        "file" -> {
          val info = messages("dataMatrix")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${messages("notExist")}",
                "url" -> Tool.fileNameCheckUrl,
                "type" -> "POST",
                "delay" -> 1000,
                "name" -> "fileName",
              ),
            )
          )
        },
        "coef" -> {
          val info = messages("coef")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "numeric" -> js.Dictionary(
                "message" -> s"${messages("numeric")}",
              ),
            )
          )
        },
        "knn" -> {
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "integer" -> js.Dictionary(
                "message" -> s"${messages("numeric")}",
              ),
              "between" -> js.Dictionary(
                "min" -> 1,
                "max" -> maxNumber,
                "message" -> s"${messages("greaterThan",0)}",
              ),
            )
          )
        },
        "min" -> {
          val info = "N"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "integer" -> js.Dictionary(
                "message" -> s"${messages("numeric")}",
              ),
              "between" -> js.Dictionary(
                "min" -> 1,
                "max" -> maxNumber,
                "message" -> s"${messages("greaterThan",0)}",
              ),
            )
          )
        },

      )
    )

    $(s"#form").bootstrapValidator(dict)
  }


}
